package org.onejava.core.bean;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.onejava.core.bean.imp.Entity;

public class ServiceEntity implements Entity{
	private String name;
	private Object obj;	
	private boolean needAop;
	
	
	private Map<String,MethodEntity> map = new HashMap<String,MethodEntity>();
	
	public List<AopEntity> getAfter(Method method) {
		MethodEntity entity = map.get(methodTokey(method));
		if(entity==null){
			return new ArrayList<AopEntity>();
		}
		return entity.getAfter();
	}
	public List<AopEntity> getAfterReturn(Method method) {
		MethodEntity entity = map.get(methodTokey(method));
		if(entity==null){
			return new ArrayList<AopEntity>();
		}
		return entity.getAfterReturn();
	}
	public List<AopEntity> getAfterThrow(Method method) {
		MethodEntity entity = map.get(methodTokey(method));
		if(entity==null){
			return new ArrayList<AopEntity>();
		}
		return entity.getAfterThrow();
	}
	public List<AopEntity> getBefore(Method method) {
		MethodEntity entity = map.get(methodTokey(method));
		if(entity==null){
			return new ArrayList<AopEntity>();
		}
		return entity.getBefore();
	}
	
	/**
	 * 设置是否需要转化为AOP代理类
	 * @param needAop
	 */
	public void setNeedAop(boolean needAop) {
		this.needAop = needAop;
	} 
	public void putMethodEntity(Method method,List<AopEntity> after,List<AopEntity> afterReturn,
			List<AopEntity> afterThrow,List<AopEntity> before){
		map.put(methodTokey(method),new MethodEntity(after, afterReturn, afterThrow, before));
	}
	private String methodTokey(Method method) {
		StringBuffer keyBuffer =new StringBuffer();
		keyBuffer.append(method.getName());
		Class<?>[] classs = method.getParameterTypes();
		for(int j=0;j<classs.length;j++){
			keyBuffer.append(classs[j].getName());
		}
		return keyBuffer.toString();
	}
	public ServiceEntity(String name, Object obj) {
		this.name = name;
		this.obj = obj;
	}
	
	public boolean isNeedAop() {
		return needAop;
		
	}
	
	public void setObj(Object obj) {
		this.obj = obj;
	}
	
	public String getName() {
		return name;
	}
	
	public Object getObj() {
		return obj;
	}
	class MethodEntity{
		 MethodEntity(
			List<AopEntity> after,
				List<AopEntity> afterReturn,
					List<AopEntity> afterThrow,
						List<AopEntity> before){
			 this.after=after;
			 this.afterReturn=afterReturn;
			 this.afterThrow=afterThrow;
			 this.before=before;
			 
		}
		 List<AopEntity> getAfter() {
			return after;
		}
		 List<AopEntity> getAfterReturn() {
			return afterReturn;
		}
		 List<AopEntity> getAfterThrow() {
			return afterThrow;
		}
		 List<AopEntity> getBefore() {
			return before;
		}
		private List<AopEntity> after;
		private List<AopEntity> afterReturn;
		private List<AopEntity> afterThrow;
		private List<AopEntity> before;		
	}
}
